package cn.conac.rc.gateway.security.service;

import java.util.Collection;
import java.util.Iterator;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;

import cn.conac.rc.framework.utils.StringUtils;
import cn.conac.rc.gateway.modules.user.entity.RoleEntity;
import cn.conac.rc.gateway.security.UserUtils;
import cn.conac.rc.gateway.security.vo.JwtUser;

/**
 * Created by haocm on 2017-5-14.
 *
 */
@Component
public class AuthCheckUtil
{
    /**
     * 查询和修改权限控制（用户id）
     * @param userId
     * @return boolean
     */
    public static boolean authCheckUserId(String userId)
    {
        //权限控制
        //系统管理员和机构域名登录允许查询其他用户信息
        JwtUser user = UserUtils.getCurrentUser();
        String currentUserId = user.getId();
        Collection<? extends GrantedAuthority> authorities = user.getAuthorities();
        if (authorities.isEmpty()) {
            // 参数baseId为null场合
            return false;
        } else {
            String role = "";
            Iterator it = authorities.iterator();
            while (it.hasNext()) {
                SimpleGrantedAuthority next = (SimpleGrantedAuthority) it.next();
                role = next.toString();
            }
            if (StringUtils.isBlank(role) || (!RoleEntity.ROLE_ADMIN_SYS.equals(role) && !RoleEntity.ROLE_CONAC_QDGLY.equals(role))) {
                //非系统管理员时候判断是否是机构域名
                // 其他用户登录只允许查询当前用户的用户信息
                String isAdmin = user.getIsAdmin();//是否是机构域名
                int userType = user.getUserType();//编办
                if (!(StringUtils.isNotBlank(isAdmin) && "1".equals(isAdmin) && (userType == 1 || userType == 3) )) {
                    if (StringUtils.isBlank(currentUserId)) {
                        return false;
                    } else {
                        if (!currentUserId.equals(userId)) {
                            // 参数baseId为null场合
                            return false;
                        }
                    }
                }
            }
        }
        return true;
    }
}
